package net.lastcoder.ifserver.route;

import net.lastcoder.ifserver.module.BaseModule;
import net.lastcoder.ifserver.module.ModuleManager;
import net.lastcoder.ifserver.module.ModuleNames;
import net.lastcoder.ifserver.packet.EventHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * auth: WenYF
 * date: 2016/10/24
 */
public class EventHandlerManager extends BaseModule {
    private static final Logger Log = LoggerFactory.getLogger(EventHandlerManager.class);

    private HashMap<Short, EventHandler> eventHandlers;
    private ModuleManager moduleManager;
    private static EventHandlerManager instance = new EventHandlerManager();

    public static EventHandlerManager getInstance() {
        return instance;
    }

    private EventHandlerManager() {
        super(ModuleNames.EventHanderManager);
        eventHandlers = new HashMap<>();
    }

    public void putEventHandler(EventHandler handler) {
        EventHandler preHandler = eventHandlers.put(handler.getEventType(), handler);
        moduleManager.addModule(handler);

        if (preHandler != null) {
            Log.warn("Exist handler when add event handler.");
            Log.warn("new handler : " + handler);
            Log.warn("previous handler : " + preHandler);
            Throwable t = new Throwable("Exist handler when add event handler.");
            Log.warn(t.getMessage(), t);
        }
    }

    public void removeEventHandler(short eventType) {
        EventHandler eventHandler = eventHandlers.remove(eventType);
        if (eventHandler != null) {
            moduleManager.removeModule(eventHandler.getName());
        }
    }

    public void removeEventHandler(EventHandler handler) {
        eventHandlers.remove(handler.getEventType());
        moduleManager.removeModule(handler);
    }

    public EventHandler getEventHandler(short eventType) {
        return eventHandlers.get(eventType);
    }

    @Override
    public void init() {
        moduleManager = ModuleManager.getInstance();
    }

    @Override
    public void reload() {
    }

    @Override
    public void destroy() {

    }
}
